#include "../../Drivers/BSP/debug_uart/debug_uart.h"

UART_HandleTypeDef debug_uart;

void MX_USART1_UART_Init(void)
{

    debug_uart.Instance = USART1;
    debug_uart.Init.BaudRate = 115200;
    debug_uart.Init.WordLength = UART_WORDLENGTH_8B;
    debug_uart.Init.StopBits = UART_STOPBITS_1;
    debug_uart.Init.Parity = UART_PARITY_NONE;
    debug_uart.Init.Mode = UART_MODE_TX_RX;
    debug_uart.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    debug_uart.Init.OverSampling = UART_OVERSAMPLING_16;

    if (HAL_UART_Init(&debug_uart) != HAL_OK)
    {
        Error_Handler();
    }

}


void DEBUG_UART_MspInit(void)
{

    GPIO_InitTypeDef GPIO_InitStruct = {0};

	/* USER CODE BEGIN USART1_MspInit 0 */

	/* USER CODE END USART1_MspInit 0 */
	/* USART1 clock enable */
	__HAL_RCC_USART1_CLK_ENABLE();

	__HAL_RCC_GPIOB_CLK_ENABLE();
	/**USART1 GPIO Configuration
	PB6     ------> USART1_TX
	PB7     ------> USART1_RX
	*/
	GPIO_InitStruct.Pin = GPIO_PIN_6 | GPIO_PIN_7;
	GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
	GPIO_InitStruct.Pull = GPIO_NOPULL;
	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
	GPIO_InitStruct.Alternate = GPIO_AF7_USART1;
	HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

}



void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle)
{

    if(uartHandle->Instance == USART1)
    {
        /* USER CODE BEGIN USART1_MspDeInit 0 */

        /* USER CODE END USART1_MspDeInit 0 */
        /* Peripheral clock disable */
        __HAL_RCC_USART1_CLK_DISABLE();

        /**USART1 GPIO Configuration
        PB6     ------> USART1_TX
        PB7     ------> USART1_RX
        */
        HAL_GPIO_DeInit(GPIOB, GPIO_PIN_6 | GPIO_PIN_7);

        /* USER CODE BEGIN USART1_MspDeInit 1 */

        /* USER CODE END USART1_MspDeInit 1 */
    }
}

/*****************  发送字符串 **********************/
void Usart_SendString(uint8_t *str)
{
    unsigned int k = 0;

    do
    {
        HAL_UART_Transmit(&debug_uart, (uint8_t *)(str + k), 1, 1000);
        k++;
    }
    while(*(str + k) != '\0');

}
///重定向c库函数printf到串口DEBUG_USART，重定向后可使用printf函数
int fputc(int ch, FILE *f)
{
    /* 发送一个字节数据到串口DEBUG_USART */
    HAL_UART_Transmit(&debug_uart, (uint8_t *)&ch, 1, 1000);

    return (ch);
}

///重定向c库函数scanf到串口DEBUG_USART，重写向后可使用scanf、getchar等函数
int fgetc(FILE *f)
{

    int ch;

    while (__HAL_UART_GET_FLAG(&debug_uart, UART_FLAG_RXNE) == RESET);

    HAL_UART_Receive(&debug_uart, (uint8_t *)&ch, 1, 1000);
    return (ch);
}
